"""
参考sa-token SaSameUtil实现
"""
from app.constants import REDIS_KEY_SAME_TOKEN, REDIS_KEY_PAST_SAME_TOKEN
from app.core.redis import redis_client as redis
from app.exception import SameTokenException


async def check_same_token(same_token: str | None) -> None:
    """ 校验same-token """
    if not await is_valid(same_token):
        raise SameTokenException(f"无效Same-Token：{same_token}")


async def is_valid(same_token: str | None) -> bool:
    """ 判断一个 Same-Token 是否有效  """
    # 1、 如果传入的 token 为空，则立即返回 false
    if same_token is None or same_token == "":
        return False

    # 2、 验证当前 Same-Token
    now_same_token = await get_token()
    now_past_same_token = await get_past_token()
    return same_token == now_same_token or same_token == now_past_same_token


async def get_token() -> str:
    """ 获取 Same-Token """
    return await redis.get(REDIS_KEY_SAME_TOKEN)


async def get_past_token() -> str:
    """ 获取 Same-Token """
    return await redis.get(REDIS_KEY_PAST_SAME_TOKEN)
